package com.sekla.design;


import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.util.concurrent.locks.LockSupport;

@Slf4j(topic = "c.TwoPhaseTermination")
public class TwoPhaseTermination {
    private Thread monitor;
    // 启动监控线程
    public void start(){
        monitor = new Thread(() -> {
            while (true) {
                Thread cur = Thread.currentThread();
                if(cur.isInterrupted()){
                    log.debug("料理后事");
                }
                try {
                    //sleep被打断会清除打断标记
                    //阻塞方法被打断会清除标记
                    Thread.sleep(1000);
                    log.debug("执行监控");
                    //catch后Interrupt打断标记为false
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //重新设置打断标记
                    cur.interrupt();
                }
            }
        });
        monitor.start();
    }
    // 停止监控线程
    public void stop(){
        monitor.interrupt();
    }


    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();

        Thread.sleep(3500);
        twoPhaseTermination.stop();
    }
}
